﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics.Contracts;
using System.Web.Security;
using System.Linq;

namespace Account
{
    public partial class account_Pay : System.Web.UI.Page
    {
        /// <summary> 不要直接访问本字段，应用CurrentUserId访问。 </summary>
        private string userId;

        public string UserId
        {
            get
            {
                if (userId == null)
                {
                    System.Diagnostics.Debug.Assert(Membership.GetUser() != null);
                    userId = Membership.GetUser().ProviderUserKey.ToString();
                }

                return userId;
            }
        }

        protected int? WantedProductId
        {
            get
            {
                if (string.IsNullOrEmpty(Request.QueryString["pid"]))
                    return null;
                else
                    return Convert.ToInt32(Request.QueryString["pid"]);
            }
        }

        protected int? WantedProductQuantity
        {
            get
            {
                if (string.IsNullOrEmpty(Request.QueryString["qty"]))
                    return null;
                else
                    return Convert.ToInt32(Request.QueryString["qty"]);
            }
        }


        protected VisitSource VisitSource
        {
            get
            {
                if (WantedProductId != null && WantedProductQuantity != null)
                    return VisitSource.ProductPage;
                else
                {
                    if (string.IsNullOrEmpty(Request.QueryString["source"]))
                        return VisitSource.Other;
                    else if (Request.QueryString["source"].Equals("shoppingcart", StringComparison.OrdinalIgnoreCase))
                        return VisitSource.ShoppingCartPage;
                    else
                        return VisitSource.Other;
                }
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (VisitSource == Account.VisitSource.Other)
                MultiView1.ActiveViewIndex = 0;
            else if (VisitSource == Account.VisitSource.ProductPage)
            {
                itemCountLabel.Text = "1";

            }
            else
            {
                productSource.SelectCommand =
    string.Format(@"
SELECT   [Shopping Cart].Quantity, vw_DiscountedProduct.*
FROM      [Shopping Cart] INNER JOIN
                vw_DiscountedProduct ON [Shopping Cart].productId = vw_DiscountedProduct.id
WHERE   ([Shopping Cart].UserId = '{0}')
", UserId);
            }

        }
        protected void confirmButton_Click(object sender, EventArgs e)
        {
            var connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"];
            if (connString == null)
                throw new ArgumentNullException("无法获取指定的数据库连接字符串。");

            using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
            {
                AddTableEntry(connection);

                //                if(VisitSource==Account.VisitSource.ProductPage)
                //                {
                //                    connection.Open();

                //                    SqlCommand command = new SqlCommand(string.Format(@"
                //SELECT   aspnet_Users.UserName
                //FROM      Shop INNER JOIN
                //                aspnet_Users ON Shop.owner = aspnet_Users.UserId INNER JOIN
                //                vw_DiscountedProduct ON Shop.name = vw_DiscountedProduct.Shop
                //WHERE   (vw_DiscountedProduct.id = {0})
                //", WantedProductId), connection);
                //                    string recipient = command.ExecuteScalar().ToString();
                //                    connection.Close();

                //                    command = new SqlCommand(string.Format(@"
                //SELECT   DiscountedPrice
                //FROM      vw_DiscountedProduct
                //WHERE   (id = {0})
                //", WantedProductId), connection);

                //                    decimal price =Convert.ToDecimal(command.ExecuteScalar());

                //                    decimal total=price*WantedProductQuantity.Value;

                //                    Profile.GetProfile(recipient).Capital += total;
                //                    Profile.Capital -= total;
                //                }
                //                else
                //                {

                //                }
            }
        }

        private void AddTableEntry(SqlConnection connection)
        {
            connection.Open();

            SqlCommand command = new SqlCommand(string.Format(@"
INSERT INTO [Sale Record]
                (UserId)
OUTPUT  inserted.id
VALUES   ('{0}')
", UserId), connection);
            command.CommandType = System.Data.CommandType.Text;
            int pk = (int)command.ExecuteScalar();

            connection.Close();
            if (VisitSource == VisitSource.ShoppingCartPage)
            {
                List<account_Shoppingcart.CartItem> cartItems = GetCartItem();

                for (int i = 0; i < cartItems.Count; i++)
                {
                    connection.Open();
                    command =
                        new SqlCommand(
                            string.Format(@"
insert into SalesItem(salesRecord,product,quantity) 
values ('{0}',{1},{2})
",
                                          pk, cartItems[i].ProductId, cartItems[i].Quantity), connection);

                    command.ExecuteNonQuery();
                    connection.Close();

                    connection.Open();
                    command =
                        new SqlCommand(
                            string.Format(@"
delete from [Shopping Cart]
where userId='{0}' and productId={1}
", UserId,
                                          cartItems[i].ProductId), connection);

                    command.ExecuteNonQuery();
                    connection.Close();
                }
            }
            else
            {
                Contract.Assert(VisitSource == Account.VisitSource.ProductPage);

                connection.Open();
                command =
                    new SqlCommand(
                        string.Format(@"
insert into SalesItem(salesRecord,product,quantity) 
values ('{0}',{1},{2})
", pk,
                                      WantedProductId, WantedProductQuantity), connection);
                command.ExecuteNonQuery();
                connection.Close();
            }
        }

        private List<account_Shoppingcart.CartItem> GetCartItem()
        {
            Contract.Ensures(Contract.Result<List<account_Shoppingcart.CartItem>>() != null);

            var connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"];
            if (connString == null)
                throw new ArgumentNullException("无法获取指定的数据库连接字符串。");


            List<account_Shoppingcart.CartItem> cartItems = new List<account_Shoppingcart.CartItem>();
            using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
            {
                connection.Open();

                SqlCommand command = new SqlCommand(
                    string.Format(@"
SELECT   [Shopping Cart].Quantity, vw_DiscountedProduct.id, vw_DiscountedProduct.name, vw_DiscountedProduct.Shop,
         vw_DiscountedProduct.coverPhoto, vw_DiscountedProduct.discountedPrice
FROM      [Shopping Cart] INNER JOIN
          vw_DiscountedProduct ON [Shopping Cart].productId = vw_DiscountedProduct.id
WHERE ([Shopping Cart].UserId = '{0}')   
", UserId), connection);
                command.CommandType = System.Data.CommandType.Text;
                var reader = command.ExecuteReader();

                while (reader.Read())
                {
                    cartItems.Add(new account_Shoppingcart.CartItem
                    {
                        Quantity = reader.GetInt32(0),
                        ProductId = reader.GetInt32(1),
                        ProductName = reader.GetString(2),
                        ProductShop = reader.GetString(3),
                        //CoverPhoto
                        ProductDiscountedPrice = reader.GetDecimal(5)
                    });
                }
            }
            return cartItems;
        }

        protected void productSource_Selected(object sender, System.Web.UI.WebControls.SqlDataSourceStatusEventArgs e)
        {
            var c = e.Command;
        }
        protected void GridView1_DataBound(object sender, EventArgs e)
        {
            itemCountLabel.Text = GridView1.Rows.Count.ToString();
        }
        protected void LinqDataSource1_Selecting(object sender, System.Web.UI.WebControls.LinqDataSourceSelectEventArgs e)
        {
            if (VisitSource == Account.VisitSource.ShoppingCartPage)
                e.Result = GetCartItem();
            else
            {
                var connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"];
                if (connString == null)
                    throw new ArgumentNullException("无法获取指定的数据库连接字符串。");

                List<account_Shoppingcart.CartItem> cartItems = new List<account_Shoppingcart.CartItem>();
                using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
                {
                    connection.Open();

                    SqlCommand command = new SqlCommand(
                        string.Format(@"
SELECT   id,name,discountedPrice,shop
FROM     vw_DiscountedProduct
WHERE id = '{0}'   
", WantedProductId), connection);
                    command.CommandType = System.Data.CommandType.Text;
                    var reader = command.ExecuteReader();

                    reader.Read();
                    cartItems.Add(new account_Shoppingcart.CartItem
                    {
                        ProductId = reader.GetInt32(0),
                        ProductName = reader.GetString(1),
                        ProductDiscountedPrice = reader.GetDecimal(2),
                        ProductShop=reader.GetString(3),
                        CoverPhoto=string.Empty,
                        Quantity = WantedProductQuantity.Value
                    });
                    e.Result = cartItems;
                }
            }
        }
    }
    /// <summary> 表示用户如何来到pay页面的枚举。 </summary>
    public enum VisitSource
    {
        ShoppingCartPage,
        ProductPage,
        Other
    }


}
